package ecoiot.com.testproject.chart;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import ecoiot.com.testproject.R;

/**
 * Created by developer on 18-1-11.
 */

public class MPLineChartActivity extends Activity {

    private LineChart mChart;

    private List<String> mTimeList = new ArrayList<>();
    private final int INVALIDATE_DATA = 921;
    private List<Float> mValues1 = new ArrayList<>();
    private List<Float> mValues2 = new ArrayList<>();
    private List<Float> mValues3 = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mp_chart);

        mChart = findViewById(R.id.mp_lc_data);

        mChart.setDescription("");

        initTimeData();

//      //设置Y轴上的单位
//      mChart.setUnit("%");
        //设置透明度
//      mChart.setAlpha(0.8f);
        //设置网格底下的那条线的颜色
//      mChart.setBorderColor(Color.rgb(213, 216, 214));
//      mChart.setBorderColor(Color.rgb(0, 0, 0));
//      mChart.setBackgroundColor(Color.rgb(255, 255, 255));
//        mChart.setGridBackgroundColor(Color.rgb(255, 255, 255));
        mChart.setBorderWidth(0);

        //设置Y轴前后倒置
//        mChart.setInvertYAxisEnabled(false);
//        //设置高亮显示
//        mChart.setHighlightEnabled(true);
        //设置是否可以触摸，如为false，则不能拖动，缩放等
        mChart.setTouchEnabled(false);
        //设置是否可以拖拽，缩放
        mChart.setDragEnabled(false);
        mChart.setScaleEnabled(false);
        //设置是否能扩大扩小
        mChart.setPinchZoom(false);
        // 设置背景颜色
//         mChart.setBackgroundColor(Color.GRAY);
        // define an offset to change the original position of the marker
        // (optional)
//        mv.setOffsets(-mv.getMeasuredWidth() / 2, -mv.getMeasuredHeight());
//        mv.setMinimumHeight(80);
//        // set the marker to the chart
//        mChart.setMarkerView(mv);
//        // enable/disable highlight indicators (the lines that indicate the
//        // highlighted Entry)
//        mChart.setHighlightIndicatorEnabled(false);
        //设置字体格式，如正楷

//        LimitLine ll1 = new LimitLine(95f, "警戒值 95%");
//        ll1.setLineWidth(2f);
//        ll1.setLineColor(Color.rgb(0,0,0));
//        ll1.enableDashedLine(10f, 10f, 0f);
//        ll1.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
//        ll1.setTextSize(15f);

        XAxis xl = mChart.getXAxis();
        xl.setAvoidFirstLastClipping(true);
        xl.setPosition(XAxis.XAxisPosition.BOTTOM); // 设置X轴的数据在底部显示
        xl.setTextSize(13f); // 设置字体大小
        xl.setSpaceBetweenLabels(0); // 设置数据之间的间距'
        xl.setDrawGridLines(false);

        YAxis yl = mChart.getAxisLeft();
        yl.setDrawLabels(true);
        yl.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        yl.setAxisMaxValue(10f);
        yl.setTextSize(13f); // s设置字体大小
        yl.setAxisMinValue(0);
        yl.setStartAtZero(true);
        yl.setLabelCount(10, false); // 设置Y轴最多显示的数据个数
        yl.setDrawGridLines(false);


        mChart.getAxisRight().setEnabled(false);
//        y2.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
//        y2.setTextSize(10f); // s设置字体大小
//        y2.setAxisMinValue(90f);
//        y2.setStartAtZero(false);

//        ArrayList<String> xVals = new ArrayList<String>();
//        for (int i = 0; i < 5; i++) {
//            xVals.add( i + "::");
//        }

        Legend legend = mChart.getLegend();
        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(12f);

        ArrayList<Entry> yVals1 = new ArrayList<>();
        ArrayList<Entry> yVals2 = new ArrayList<>();
        ArrayList<Entry> yVals3 = new ArrayList<>();

        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            float v1 = Math.abs(random.nextFloat() * 10);
            float v2 = Math.abs(random.nextFloat() * 10);
            float v3 = Math.abs(random.nextFloat() * 10);
            mValues1.add(v1);
            mValues2.add(v2);
            mValues3.add(v3);
            yVals1.add(new Entry(v1, i));
            yVals2.add(new Entry(v2, i));
            yVals3.add(new Entry(v3, i));
        }

        setData(yVals1, yVals2, yVals3);

        handler.sendEmptyMessageDelayed(INVALIDATE_DATA, 5000);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == INVALIDATE_DATA) {
                invalidateData();
                handler.sendEmptyMessageDelayed(INVALIDATE_DATA, 5000);
            }
        }
    };

    /*private void invalidateData() {
        Random random = new Random();
        mValues1.remove(0);
        mValues1.add(Math.abs(random.nextFloat() * 10));
        ArrayList<Entry> yVals = new ArrayList<>();
        for (int i = 0; i < mValues1.size(); i ++) {
            yVals.add(new Entry(mValues1.get(i), i));
        }

        mTimeList.remove(0);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        String date = sdf.format(new Date(System.currentTimeMillis()));
        mTimeList.add(date);

        setData(yVals);
        mChart.invalidate();
    }*/

    private void invalidateData() {
        Random random = new Random();
        mValues1.remove(0);
        mValues2.remove(0);
        mValues3.remove(0);
        mValues1.add(Math.abs(random.nextFloat() * 10));
        mValues2.add(Math.abs(random.nextFloat() * 10));
        mValues3.add(Math.abs(random.nextFloat() * 10));
        ArrayList<Entry> yVals1 = new ArrayList<>();
        ArrayList<Entry> yVals2 = new ArrayList<>();
        ArrayList<Entry> yVals3 = new ArrayList<>();
        for (int i = 0; i < mValues1.size(); i ++) {
            yVals1.add(new Entry(mValues1.get(i), i));
            yVals2.add(new Entry(mValues2.get(i), i));
            yVals3.add(new Entry(mValues3.get(i), i));
        }

        mTimeList.remove(0);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        String date = sdf.format(new Date(System.currentTimeMillis()));
        mTimeList.add(date);

        setData(yVals1, yVals2, yVals3);
        mChart.invalidate();
    }

    private void setData(ArrayList<Entry> yVals) {
        // create a dataset and give it a type
        LineDataSet set1 = new LineDataSet(yVals, "电压变化曲线（V）");

        set1.setDrawCubic(true);  //设置曲线为圆滑的线
        set1.setCubicIntensity(0.2f);
        set1.setDrawFilled(false);  //设置包括的范围区域填充颜色
        set1.setDrawCircles(true);  //设置有圆点
        set1.setLineWidth(2f);    //设置线的宽度
        set1.setCircleSize(5f);   //设置小圆的大小
        set1.setCircleColor(Color.rgb(244, 117, 117));
//        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setColor(Color.rgb(244, 117, 117));    //设置曲线的颜色

        // create a data object with the datasets
        LineData data = new LineData(mTimeList, set1);

        // set data
        mChart.setData(data);

    }

    private void setData(ArrayList<Entry> yVals1, ArrayList<Entry> yVals2, ArrayList<Entry> yVals3) {
        // create a dataset and give it a type
        LineDataSet set1 = new LineDataSet(yVals1, "A相电压变化曲线（V）");

        set1.setDrawCubic(false);  //设置曲线为圆滑的线
        set1.setCubicIntensity(0.2f);
        set1.setDrawFilled(false);  //设置包括的范围区域填充颜色
        set1.setDrawCircles(true);  //设置有圆点
        set1.setLineWidth(2f);    //设置线的宽度
        set1.setCircleSize(5f);   //设置小圆的大小
        set1.setCircleColor(Color.rgb(244, 117, 117));
//        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setColor(Color.rgb(244, 117, 117));    //设置曲线的颜色

        LineDataSet set2 = new LineDataSet(yVals2, "B相电压变化曲线（V）");

        set2.setDrawCubic(false);  //设置曲线为圆滑的线
        set2.setCubicIntensity(0.2f);
        set2.setDrawFilled(false);  //设置包括的范围区域填充颜色
        set2.setDrawCircles(true);  //设置有圆点
        set2.setLineWidth(2f);    //设置线的宽度
        set2.setCircleSize(5f);   //设置小圆的大小
        set2.setCircleColor(Color.rgb(117, 244, 117));
//        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set2.setColor(Color.rgb(117, 244, 117));    //设置曲线的颜色

        LineDataSet set3 = new LineDataSet(yVals3, "C相电压变化曲线（V）");

        set3.setDrawCubic(false);  //设置曲线为圆滑的线
        set3.setCubicIntensity(0.2f);
        set3.setDrawFilled(false);  //设置包括的范围区域填充颜色
        set3.setDrawCircles(true);  //设置有圆点
        set3.setLineWidth(2f);    //设置线的宽度
        set3.setCircleSize(5f);   //设置小圆的大小
        set3.setCircleColor(Color.rgb(117, 117, 244));
//        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set3.setColor(Color.rgb(117, 117, 244));    //设置曲线的颜色

        List<LineDataSet> sets = new ArrayList<>();
        sets.add(set1);
        sets.add(set2);
        sets.add(set3);

        // create a data object with the datasets
        LineData data = new LineData(mTimeList, sets);
        data.setDrawValues(false);

        // set data
        mChart.setData(data);

    }

    private void initTimeData() {
        long currentTime = System.currentTimeMillis();

        for (int i = 7; i >= 0; i --) {
//            DateFormat dateFormat = SimpleDateFormat.getTimeInstance(DateFormat.MEDIUM);
            long time = currentTime - (3600 * 10 * i);
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
            String date = sdf.format(new Date(time));
//            String date = dateFormat.format(new Date(time));

            mTimeList.add(date);
        }
    }
}
